package com.example.zbh.dsliao.ui.activty;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.util.EMLog;
import com.easemob.util.PathUtil;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.presenter.BasePresenter;
import com.example.zbh.dsliao.utils.DlUser;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.utils.UserProfileManager;
import com.example.zbh.dsliao.view.CustomDialog;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 个人资料设置界面
 */
public class SetPersonnalActivity extends MVPBaseActivity implements View.OnClickListener {

    private static final String CONFIG_TABLE_NAME = "geanwen";
    private static final String CONFIG_USERNAME = "username";
    private static final String CONFIG_NICK = "nickname";

    private ImageView backSetPersonal, userAvatar;
    private Button changeBtn, takeBtn, yesBtn, alterBtn, ensureBtn;
    private TextView usernameTv;
    private LinearLayout alterLayout;
    private EditText inputEt;
    private PreferenceHelper preferenceHelper;
    private CustomDialog customDialog;
    private CustomDialog customD;
    private Map<String, DlUser> contactList;
    private File cameraFile;//相册文件
    @Override
    protected BasePresenter createPresenter() {
        return new BasePresenter();
    }

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        EventBus.getDefault().register(this);
    }

    /**
     * 监听主界面的eventbus发过来的的状态
     * (包括 1 == 账号被服务器删除
     * 2 == 账号被别的设备登录)
     * **/
    public void onEventMainThread(Integer data){
        if (data == 2){
            DliaoUtils.showDialogConnection(this);
        }else if (data == 1){
            DliaoUtils.showDialogUserRemoved(this);
        }
    }

    @Override
    protected int getLayOut() {
        return R.layout.activity_setpersonal;
    }


    @Override
    protected void initView() {
        backSetPersonal = findeView(R.id.backSetPersonal);
        changeBtn = findeView(R.id.changeBtn);
        changeBtn.getBackground().setAlpha(100);
        takeBtn = findeView(R.id.takeBtn);
        takeBtn.getBackground().setAlpha(100);
        usernameTv = findeView(R.id.usernameTv);
        userAvatar = findeView(R.id.userAvatar);
        alterBtn = findeView(R.id.alterBtn);
        alterLayout = findeView(R.id.alterLayout);
        ensureBtn = findeView(R.id.ensureBtn);
        inputEt = findeView(R.id.inputEt);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        String username = intent.getStringExtra("username");
        preferenceHelper = PreferenceHelper.getInstance();
        backSetPersonal.setOnClickListener(this);
        takeBtn.setOnClickListener(this);
        changeBtn.setOnClickListener(this);
        alterBtn.setOnClickListener(this);
        ensureBtn.setOnClickListener(this);

        String name = preferenceHelper.getThreeCurrentUserNick();
        String avater = preferenceHelper.getThreeCurrentUserAvatar();
        if (name != null){
            usernameTv.setText(name);
        }
        if (avater != null){
            setUserAvatar(this, avater, userAvatar);
        }

    }

    /**
     * 设置头像
     * **/
    private void setUserAvatar(Context context, String avater, ImageView userImg) {
        if (avater != null){
            Glide.with(context).load(avater).into(userImg);
            Log.d("wonima", "wonima" + ">>>>>");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backSetPersonal:
                this.finish();
                break;
            case R.id.changeBtn://手机相册照片
                toPhotoGallery();
                break;
            case R.id.takeBtn://拍照上传
                tophotoCapture();
                break;
            case R.id.alterBtn://修改昵称按钮
                alterBtn.setVisibility(View.GONE);
                alterLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.ensureBtn://确定修改昵称按钮
                    clickensureBtn();
                break;
        }
    }


    //手机摄像头
    private void tophotoCapture() {
        //检测sd卡是否存在
       if (!DliaoUtils.isExitsSdcard()){
           Toast.makeText(this, "sd卡不存在", Toast.LENGTH_SHORT).show();
           ;
           return;
       }
        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMChatManager.getInstance().getCurrentUser() + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)), 250);
    }

    //手机相册
    private void toPhotoGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 200);
    }

    /**
     * 点击确定修改昵称按钮
     * **/
    private void clickensureBtn() {
        //获得输入的昵称
        String nickName = inputEt.getText().toString();
        if (nickName != null && nickName.length() > 0){
            customDialog = new CustomDialog(this, "玩命修改中..");
            customDialog.show();
            updataRemoteNick(nickName);
        }else {
            Toast.makeText(this, "昵称不能为空!", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上传昵称
     * **/
    private void updataRemoteNick(String nickName) {
        boolean updatenick = updateCurrentUserNickName(nickName);
        if (SetPersonnalActivity.this.isFinishing()){
            return;
        }
        if (!updatenick){
            customDialog.dismiss();
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }else {
            customDialog.dismiss();
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            usernameTv.setText(nickName);
        }
    }


    /**
     * 保存昵称 应该是改变缓存当前的用户名
     * **/
    public boolean updateCurrentUserNickName(final String nickname){
        boolean isSuccess = updateParseNickName(nickname);
        if (isSuccess){
            preferenceHelper.setThreeCurrentUserNick(nickname);
        }
        return isSuccess;
    }



    /**
     * 保存昵称 返回boolean值
     * **/
    public boolean updateParseNickName(final String nickname){
        String username = EMChatManager.getInstance().getCurrentUser();
        ParseQuery<ParseObject> query = ParseQuery.getQuery(CONFIG_TABLE_NAME);
        query.whereEqualTo(CONFIG_USERNAME, username);
        ParseObject object = null;
        try {
            object = query.getFirst();
            if (object == null){
                return false;
            }
            object.put(CONFIG_NICK, nickname);
            object.save();
            return true;
        } catch (ParseException e) {
            object = new ParseObject(CONFIG_TABLE_NAME);
            object.put(CONFIG_USERNAME, username);
            object.put(CONFIG_NICK, nickname);
            try {
                object.save();
                return true;
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0){
            return;
        }
        if (data == null) {
            return;
        }
        switch (requestCode) {
            case 200:
                startPhotoZoom(data.getData());
                break;
            case 100:
                setPicToView(data);
                break;
            case 250:
                startPhotoZoom(data.getData());
                break;
        }
    }


    //对图片进行裁剪
    private void startPhotoZoom(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 100);
    }

    /**
     * 从相册返回的图片设置到view上
     **/
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            ByteArrayOutputStream bos = null;
            try {
                Bitmap bitmap = bundle.getParcelable("data");
                Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                userAvatar.setImageDrawable(drawable);
                bos = new ByteArrayOutputStream();
                //压缩
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                Log.i("test","---->>>"+data.length);
                //上传
                uploadUserAvatar(data);

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (bos != null){
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    private void uploadUserAvatar(final byte[] bytes) {
        customD = new CustomDialog(this, "玩命上传中...");
        customD.setCanceledOnTouchOutside(false);
        customD.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String avatarUrl = uploadParseAvatar(bytes);
                if (avatarUrl != null){
                    preferenceHelper.setThreeCurrentUserAvatar(avatarUrl);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        customD.dismiss();
                        if (avatarUrl != null){
                            Toast.makeText(SetPersonnalActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(SetPersonnalActivity.this, "修改失败!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();

    }

    /**
     * 上传头像 到第三方parse
     * **/
    private String uploadParseAvatar(byte[] bytes) {
        String userName = EMChatManager.getInstance().getCurrentUser();
        ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
        pQuery.whereEqualTo("username", userName);
        ParseObject pUser = null;
        try {
            pUser = pQuery.getFirst();
            if (pUser == null){
                pUser = new ParseObject(CONFIG_TABLE_NAME);
                pUser.put("username", userName);
            }
            ParseFile pFile = new ParseFile(bytes);
            pUser.put("avatar", pFile);
            pUser.save();
            return pFile.getUrl();
        } catch (ParseException e)
        {
            Log.i("test","------->>>366");
            e.printStackTrace();
            if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
                try {
                    pUser = new ParseObject(CONFIG_TABLE_NAME);
                    pUser.put("username", userName);
                    ParseFile pFile = new ParseFile(bytes);
                    pUser.put("avatar", pFile);
                    pUser.save();
                    return pFile.getUrl();
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
            } else {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.i("test","------->>>383");
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (customD != null){
            customD.dismiss();
        }
    }
}
